<?php


Class pdoMysql
{

    private static $_instance;

    private $_configFile;
    private $_config;
    private $_sdn;
    private $_dbh;
    private $_username;
    private $_password;


    private function __construct()
    {
        $this->_configFile = './config.php';
        $config = $this->addConfig('db');
        $this->_sdn = "mysql:host=".$config['hostname'].";dbname=".$config['database'];
        $this->_username = $config['username'];
        $this->_password = $config['password'];
        $this->connect();
        $this->_dbh->query('SET NAMES '.$config['charset']);
    }

    public function __clone()
    {
        trigger_error('Clone is not allow!',E_USER_ERROR);
    }


    public static function getInstance()
    {
        if(!(self::$_instance instanceof self)){
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    /**
     * 数据库连接
     *
     */
    private function connect()
    {
        try
        {
            $this->_dbh = new PDO($this->_sdn, $this->_username,$this->_password);
        }
        catch (Exception $e)
        {
            exit('连接失败:'.$e->getMessage());
        }
    }


    /**
     * 数据插入
     *
     * @param  arr $data      [description]
     *
     * @param  str $tableName [description]
     *
     */
    public function insert($data,$tableName)
    {

        if(is_array($data)){

            $field = implode(",",array_keys($data));
            $value = "'".implode("','",array_values($data))."'";
        }
        $value = $this->_encoding($value);
        $sql   = "INSERT INTO $tableName($field) VALUES($value)";
        $query = $this->_dbh->query($sql);

        if(!$query){
            $this->_pdoError();
        }


    }


    /**
     * 加载配置文件
     *
     * @param string $num [description]
     */
    public function addConfig($type='')
    {
         if(!($this->_config)){

            $this->_config = include $this->_configFile;
         }
         $data = $this->_config;

         return $data[$type];
    }


    /**
     * 转换为utf8 编码
     *
     * @param  str $str [description]
     *
     * @return str
     */
    private function _encoding($str)
    {

        foreach (array('GBK', 'UTF-8') as $v) {

            if ($str === iconv($v, $v . '//IGNORE', $str)) {
               return iconv($v, 'UTF-8//IGNORE', $str);
            }
        }
    }


    /**
     * pdoError
     *
     * @return [type] [description]
     */
    private function _pdoError()
    {
        if($this->_dbh->errorCode() != '00000') {

            $error = $this->_dbh->errorInfo();
            exit($error[2]);
        }
    }

    public function __destrcut()
    {
        $this->$this->_dbh = null;
    }


}


